package com.pig4cloud.pigx.wallet.api.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.api.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.api.util.OpenApiUtil;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.wallet.api.v1.service.CapitalAccountServiceV1;
import com.pig4cloud.pigx.wallet.api.v1.utils.WalletUtilsV1;
import com.pig4cloud.pigx.wallet.entity.CapitalAccount;
import com.pig4cloud.pigx.wallet.mapper.CapitalAccountMapper;
import com.pig4cloud.pigx.wallet.websocket.AssetListVo;
import com.pig4cloud.pigx.wallet.websocket.CapitalAccountVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 */
@Service
@AllArgsConstructor
public class CapitalAccountServiceImplV1 extends ServiceImpl<CapitalAccountMapper, CapitalAccount> implements CapitalAccountServiceV1 {

	private final WalletUtilsV1 utils;

	/**
	 * 获取资金账户余额
	 *
	 * @return 余额
	 */
	public R<CapitalAccountVo> getBalance() {
		// 获取用户
		PigxUser user = utils.getUser();
		try {
			CapitalAccount account = baseMapper.selectOne(new QueryWrapper<CapitalAccount>() {{
				eq("user_id", user.getId());
			}});
			CapitalAccountVo capitalAccountVo = new CapitalAccountVo();
			AssetListVo assetListVo = new AssetListVo();
			List<AssetListVo> list = new ArrayList<>();
			// 类型转换
			assetListVo.setCurrency("USDT");
			assetListVo.setAvailable(account.getAvailable().setScale(2, RoundingMode.DOWN).toPlainString());
			assetListVo.setFrozen(account.getFrozen().setScale(2, RoundingMode.DOWN).toPlainString());
			BigDecimal total = account.getAvailable().add(account.getFrozen()).setScale(2, RoundingMode.DOWN);
			assetListVo.setTotal(total.toPlainString());
			list.add(assetListVo);
			capitalAccountVo.setAssetList(list);
			capitalAccountVo.setTotalAssets(assetListVo.getTotal());
			return R.ok(capitalAccountVo);
		} catch (Exception e) {
			throw OpenApiUtil.getError(AbnormalEnum.MSG.DISCONNECTED);
		}
	}

}
